package com.ailanyin.admin.service.impl;

import com.ailanyin.admin.service.SysDictTypeService;
import com.ailanyin.admin.service.SysUserService;
import com.ailanyin.common.exception.Asserts;
import com.ailanyin.common.service.RedisService;
import com.ailanyin.common.utils.StringUtil;
import com.ailanyin.mapper.SysDictDataMapper;
import com.ailanyin.mapper.SysDictTypeMapper;
import com.ailanyin.model.SysDictData;
import com.ailanyin.model.SysDictType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 17:05
 */
@Service
public class SysDictTypeServiceImpl implements SysDictTypeService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Resource
    private SysDictDataMapper dictDataMapper;
    @Resource
    private SysDictTypeMapper dictTypeMapper;

    @Value("${redis.database}")
    private String database;

    private static final String KEY = ":sys:dict:";
    private static final String DEL_ALL_KEY = ":sys:dict";

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {

        if (redisService.get(database + KEY + dictType) != null) {
            return (List<SysDictData>) redisService.get(database + KEY + dictType);
        }
        List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType(dictType);
        if (dictDataList.size() > 0) {
            addToRedis(dictType, dictDataList);
        }
        return dictDataList;

    }


    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType) {
        return dictTypeMapper.selectDictTypeList(dictType);
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId) {
        return dictTypeMapper.selectDictTypeById(dictId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDictType(SysDictType dictType) {
        if (checkDictTypeNotUnique(dictType)) {
            Asserts.fail("新增字典'" + dictType.getDictName() + "'失败，字典类型已存在");
        }

        dictType.setCreateBy(sysUserService.getCurrentUser().getUserName());
        dictType.setCreateTime(new Date());
        dictTypeMapper.insertDictType(dictType);

    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dictType 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeNotUnique(SysDictType dictType) {
        SysDictType sysDictType = dictTypeMapper.checkDictTypeUnique(dictType.getDictType());
        return StringUtil.isNotNull(sysDictType) && !sysDictType.getDictId().equals(dictType.getDictId());
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDictType(SysDictType dictType) {

        if (checkDictTypeNotUnique(dictType)) {
            Asserts.fail("修改字典'" + dictType.getDictName() + "'失败，字典类型已存在");
        }

        SysDictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId());
        dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType());
        int row = dictTypeMapper.updateDictType(dictType);
        if (row > 0) {
            List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType(dictType.getDictType());
            addToRedis(dictType.getDictType(), dictDataList);
        }

    }

    /**
     * 批量删除字典信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
                Asserts.fail(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dictTypeMapper.deleteDictTypeById(dictId);
            delFromRedis(dictType.getDictType());
        }
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        Collection<String> keys = redisService.getKeys(database + KEY + "*");
        List<String> keyList = new ArrayList<>(keys);
        redisService.del(keyList);
        loadingDictCache();
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        List<SysDictType> dictTypeList = dictTypeMapper.selectDictTypeAll();
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType(dictType.getDictType());
            addToRedis(dictType.getDictType(), dictDataList);
        }
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return dictTypeMapper.selectDictTypeAll();
    }

    private void addToRedis(String dictType, List<SysDictData> dictDataList) {
        redisService.set(database + KEY + dictType, dictDataList);
    }

    private void delFromRedis(String dictType) {
        redisService.del(database + KEY + dictType);
    }
}
